package com.topdt.jbpm.dao;


import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.springframework.stereotype.Repository;

import com.thx.common.orm.PaginationDao;
import com.thx.common.util.AppContext;
import com.topdt.jbpm.model.Application;

/**
 * 建立日期 : Jul 27, 2012 6:02:00 PM<br>
 * 作者 : 贾红磊<br>
 * 模块 : <br>
 * 描述 : <br>
 * 修改历史: 序号 日期 修改人 修改原因 <br>
 * 1 <br>
 * 2 <br>
 */
@Repository
public class ApplicationDao extends PaginationDao<Application> {

  @SuppressWarnings("unchecked")
  public Application getById(String Id) {
    String comId = AppContext.getCurrentComId();
    String condition = "";
    if (comId != null && !"".equals(comId))
      condition = "companyId='" + comId + "' and ";
    String hql = "from Application where " + condition + " appId = ? ";
    List<Application> list = createQuery(hql, new Object[] {Id}).list();
    if (list.size() > 0)
      return (Application) list.get(0);

    return null;
  }

  @SuppressWarnings("unchecked")
  public List<Application> findAppsByType(String typeId) {
    String comId = AppContext.getCurrentComId();
    String condition = "";
    if (comId != null && !"".equals(comId))
      condition = "companyId='" + comId + "' and ";
    String hql = "from Application where " + condition + " appType.typeId =? and isValid='1'";
    hql += "  order by appOrder asc";
    List<Application> list = createQuery(hql, new Object[] {typeId}).list();
    if (list.size() > 0)
      return list;

    return null;
  }

  @SuppressWarnings("unchecked")
  public Application getAppName(String appName, String companyId) {
    String hql = "from Application where appName = ? and isValid = '1' and companyId=?";
    List<Application> list = createQuery(hql, new Object[] {appName, companyId}).list();
    if (list != null && list.size() > 0) {
      return list.get(0);
    }
    return null;
  }

  @SuppressWarnings("unchecked")
  public Application getByCompanyId(String companyId) {
    String hql =
        "from Application app where   app.isValid='1' and app.companyId ='" + companyId + "'";
    List<Application> list = createQuery(hql).list();
    if (list != null && list.size() > 0) {
      return list.get(0);
    }
    return null;
  }

  @SuppressWarnings("unchecked")
  public List<Application> queryAll(Application entity, int start, int max) {
    String hql =
        "from Application app where app.isValid='1' and app.companyId = ? order by app.isInherent desc,app.appId";
    List<Application> list =
        createQuery(hql, entity.getCompanyId()).setFirstResult(start).setMaxResults(max).list();
    if (list.size() > 0)
      return list;
    return null;
  }

  public int queryCount() {
    String comId = AppContext.getCurrentComId();
    String condition = "";
    if (comId != null && !"".equals(comId))
      condition = "company_id='" + comId + "' and ";
    String sql = "select count(*) from wf_application where " + condition + "IS_VALID = '1'";
    return Integer.parseInt(createSqlQuery(sql).list().get(0).toString());
  }

  @SuppressWarnings("unchecked")
  public List<Application> listDocumentApps() {
    String comId = AppContext.getCurrentComId();
    String hql =
        "from Application app where app.companyId =? and app.isValid='1' and app.appAttr='1'";
    List<Application> list = createQuery(hql, new Object[] {comId}).list();
    if (list != null && list.size() > 0) {
      return list;
    }
    return null;

  }

  /**
   * 获取application模板数据并插入表里
   */
  public void addApp(String companyId) throws HibernateException {
    String sql =
        "insert into wf_application w (w.APP_ID,w.APP_DESCRIBE,w.APP_NAME,w.APP_TYPE,w.FLOW_ID,w.FLOW_KEY,w.FORM_ID,w.HANDLE_ID,w.COMPANY_ID,w.IS_INHERENT,w.IS_VALID,w.APP_ATTR,w.DOC_TEMPATH) "
            + " select :companyId||sw.APP_ID,sw.APP_DESCRIBE,sw.APP_NAME,:companyId||sw.APP_TYPE,sw.FLOW_ID,sw.FLOW_KEY,:companyId||sw.FORM_ID,sw.HANDLE_ID,:companyId,sw.IS_INHERENT,sw.IS_VALID,sw.APP_ATTR,sw.DOC_TEMPATH "
            + " from sys_wf_application sw";
    SQLQuery sqlQ = (SQLQuery) createSqlQuery(sql).setString("companyId", companyId);
    sqlQ.executeUpdate();
  }

  /**
   * 客户端查询应用列表
   * 
   * @author zhangyong
   * @date 2015年12月23日 下午6:54:04
   * @param comId
   * @param isInherent
   * @param appType
   * @return
   */
  @SuppressWarnings("unchecked")
  public List<Application> listApps(String comId, String isInherent, String appType) {
    String hql =
        "from Application app where app.companyId=? and app.isValid='1' and app.isInherent=?";
    if ("document".equalsIgnoreCase(appType)) {
      hql += " and  (app.appAttr='1' or app.appAttr='3' or app.appAttr='5')   )";
    } else if ("ticket".equalsIgnoreCase(appType)) {
      hql += " and  (app.appAttr='0' or app.appAttr='2' or app.appAttr='4')  )";
    }
    List<Application> list = createQuery(hql, comId, isInherent).list();
    return list;
  }


  /**
   * 通过应用类型查找应用
   * 
   * @author 冯晋首
   * @date 2016年3月18日 下午4:38:53
   * @param comId
   * @param appType
   * @return
   */
  @SuppressWarnings("unchecked")
  public List<Application> findAppsByType(String comId, String appType) {
    String hql = "from Application app where app.companyId=? and app.isValid='1'";
    if ("document".equalsIgnoreCase(appType)) {
      hql += " and  (app.appAttr='1' or app.appAttr='3' or app.appAttr='5')   )";
    } else if ("ticket".equalsIgnoreCase(appType)) {
      hql += " and  (app.appAttr='0' or app.appAttr='2' or app.appAttr='4')  )";
    }
    List<Application> list = createQuery(hql, comId).list();
    return list;
  }

  /**
   * 查询应用的数量
   * 
   * @author zhangyong
   * @date 2013-12-18 上午10:12:15
   * @param id
   * @return
   */
  /*
   * public int queryAppNum(String id,CommonLogView commonLogView) { StringBuilder sql = new
   * StringBuilder(); Object[] o = new Object[]{id};
   * sql.append(" select count(*) tongji from wf_application tt "); sql.append(
   * " where tt.company_id in (select e.enterprise_id from enterprise e where e.enterprise_id >? and e.enterprise_number not like '%test%') "
   * ); if(StringUtils.isNotBlank(commonLogView.getCityStr())){ String[] cityStrings =
   * commonLogView.getCityStr().split(","); String cityString=""; for(String city: cityStrings){
   * if(cityString.equals("")){ cityString = "'"+city.trim()+"'"; }else{ cityString +=
   * ",'"+city.trim()+"'"; } }
   * sql.append(" and tt.company_id in ( select e.enterprise_id from enterprise e where e.BIZ_CITY in("
   * +cityString+") ) "); } Object obj = createSQLQuery(sql.toString(),o).uniqueResult();
   * if(obj!=null){ return Integer.parseInt(obj.toString()); }else{ return 0; } }
   */
  /**
   * @author 贺晋恩
   * @date 2014-2-13 下午4:00:24
   * @param enterpriseId
   * @param startdate2
   * @param enddate2
   * @param mODULE_EXTAPP
   * @return
   */
  public int queryByEntId(Long enterpriseId) {
    StringBuilder sql = new StringBuilder();
    Object[] o = new Object[] {enterpriseId};
    sql.append(" select count(*) tongji from wf_application tt");
    sql.append(" where tt.company_id = ?");
    Object obj = createSqlQuery(sql.toString(), o).uniqueResult();
    if (obj != null) {
      return Integer.parseInt(obj.toString());
    } else {
      return 0;
    }
  }

  /**
   * 
   * <b>Method getAppsByComId</b> <dd>方法作用：(通过企业id查找有效的应用列表)
   * 
   * @param comId 公司id
   * @author Wangxufeng
   * @date 2014-12-02
   * @return
   * @since Met 1.0
   */
  public List<Application> getAppsByComId(String comId) {
    String hql = "from Application app where app.companyId=? and app.isValid='1'";
    @SuppressWarnings("unchecked")
    List<Application> list = createQuery(hql, comId).list();
    return list;
  }

  /**
   * 
   * @author _zili
   * @Description:app的分页方法
   * @date 2015年3月30日 上午10:10:37
   */
  public List<Application> getAppsPageByComId(String appName) {
    List<Object> params = new ArrayList<Object>();
    String comId = AppContext.getCurrentComId();
    params.add(comId);
    String hql = "from Application app where app.companyId=? and app.isValid='1' ";
    if (StringUtils.isNotBlank(appName)) {
      hql += " and app.appName like ?";
      params.add("%" + appName + "%");
    }
    // fengjinshou 20151229 按appOrder排序
    hql += "  order by app.appOrder asc,app.createTime desc";
    return findPageList(hql, params.toArray());

  }

}
